package com.smart.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.smart.entity.EnvironmentData;
import com.smart.entity.Sensor;
import com.smart.mapper.EnvironmentDataMapper;
import com.smart.service.IEnvironmentDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smart.service.ISensorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 环境数据 服务实现类
 * </p>
 *
 * @author Cookies
 * @since 2024-05-19
 */
@Service
public class EnvironmentDataServiceImpl extends ServiceImpl<EnvironmentDataMapper, EnvironmentData> implements IEnvironmentDataService {
    @Autowired
    private ISensorService sensorService;

    @Override
    public IPage<EnvironmentData> getEnvironmentDataByType(Integer current, Integer size, String type) {
        IPage<Sensor> page = new Page(current, size);
        IPage<Sensor> sensorPage = sensorService.lambdaQuery().eq(!"all".equals(type), Sensor::getType, type)
                .page(page);
        List<Integer> idList = sensorPage.getRecords().stream()
                .map(sensor -> sensor.getId())
                .collect(Collectors.toList());
        List<EnvironmentData> latestData = new ArrayList<>();
        for (Integer id : idList) {
            EnvironmentData environmentData = lambdaQuery().eq(EnvironmentData::getDeviceId, id)
                    .orderByDesc(EnvironmentData::getDeviceTime)
                    .last("limit 1")
                    .one();
            latestData.add(environmentData);
        }
        IPage<EnvironmentData> environmentDataPage = new Page(current, size);
        environmentDataPage.setRecords(latestData);
        environmentDataPage.setTotal(sensorPage.getTotal());
        return environmentDataPage;
    }

    @Override
    public List<EnvironmentData> getEnvironmentDataById(Integer device_id) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String date = LocalDateTime.now().minusWeeks(1).format(formatter);
        List<EnvironmentData> environmentDataList = lambdaQuery().eq(EnvironmentData::getDeviceId, device_id)
                .ge(EnvironmentData::getDeviceTime, date)
                .orderByDesc(EnvironmentData::getDeviceTime)
                .list();
        return environmentDataList;
    }
}
